package cn.jsc.controller;

import cn.jsc.doc.CourseDoc;
import cn.jsc.dto.CourseQueryDto;
import cn.jsc.respo.CourseElasticsearchRepository;
import cn.jsc.result.JSONResult;
import cn.jsc.result.PageList;
import cn.jsc.service.ESService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/es")
public class ESController {

    @Autowired
    private CourseElasticsearchRepository repository;

    @Autowired
    private ESService esService;

    /**
     * 课程搜索
     */
    @PostMapping("/searchCourse")
    public JSONResult searchCourse(@RequestBody CourseQueryDto dto){
        PageList<CourseDoc> pageList = esService.searchCourse(dto);
        return JSONResult.success(pageList);
    }
    /**
     * 往ES中存单个数据
     */
    @PostMapping("/saveCourse")
    public JSONResult insert(@RequestBody CourseDoc doc){
        //保存到ES中去
        repository.save(doc);
        return JSONResult.success();
    }
    /**
     * 往ES中批量存数据
     */
    @PostMapping("/saveBatchCourse")
    @PreAuthorize("hasAuthority('es:saveCourse')")
    public JSONResult insertBatch(@RequestBody List<CourseDoc> list){
        System.out.println("课程批量上线");
        //保存到ES中去
        repository.saveAll(list);
        return JSONResult.success();
    }

    /**
     * 对ES中批量删除数据
     */
    @PostMapping("/deleteBatchCourse")
    public JSONResult deleteBatch(@RequestBody List<CourseDoc> list){
        //ES中批量删除数据
        repository.deleteAll(list);
        return JSONResult.success();
    }
}
